from django.db.models import Count
from home import models

# 计算每个商品的权重
def recommended_products(jobposting_ids):
    # 统计行为数据  筛选+分组+统计  以职位id为分组统计数据
    browse_counts = models.BrowseJobposting.objects.filter(
        jobposting__in=jobposting_ids
    ).values('jobposting').annotate(count=Count('id'))
    collect_counts = models.CollectJobposting.objects.filter(
        jobposting__in=jobposting_ids
    ).values('jobposting').annotate(count=Count('id'))
    deliver_counts = models.DeliverJobposting.objects.filter(
        jobposting__in=jobposting_ids
    ).values('jobposting').annotate(count=Count('id'))

    # 整合数据 计算热度
    WEIGHTS = {'browse': 0.4, 'collect': 0.3, 'deliver': 0.3}
    job_stats = {}

    # 处理浏览
    for item in browse_counts:
        job_id = item['jobposting']
        # 第一次执行 job_id=1不存在 插入key=1 值为{}
        job_stats.setdefault(job_id, {})['browse'] = item['count']

    # 处理收藏
    for item in collect_counts:
        job_id = item['jobposting']
        job_stats.setdefault(job_id, {})['collect'] = item['count']

    # 处理投递
    for item in deliver_counts:
        job_id = item['jobposting']
        job_stats.setdefault(job_id, {})['deliver'] = item['count']

    # 结果：得到每个招聘信息的数据
    # job_stats = {
    #     1: {'browse': 100, 'collect': 20},
    #     2: {'browse': 80, 'collect': 15}
    # }

    # 计算热度
    hot_jobs = []
    for job_id, stats in job_stats.items():
        browse = stats.get('browse', 0)
        collect = stats.get('collect', 0)
        deliver = stats.get('deliver', 0)

        hot_score = browse * 0.4 + collect * 0.3 + deliver * 0.3
        hot_jobs.append({
            'jobposting_id': job_id,
            'hot_score': hot_score,
            'browse': browse,
            'collect': collect,
            'deliver': deliver
        })
    # 按热度排序--直接修改职位列表本身
    hot_jobs.sort(key=lambda x: x['hot_score'], reverse=True)
    return hot_jobs[:9]